package arrAndstr;

/*
    112. 路径总和
 */
public class T112 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(5);
        node.left = new TreeNode(4);
        node.left.left = new TreeNode(11);
        node.left.left.left = new TreeNode(7);
        node.left.left.right = new TreeNode(2);
        node.right = new TreeNode(8);
        node.right.left = new TreeNode(13);
        node.right.right = new TreeNode(4);
        node.right.right.right = new TreeNode(1);

        System.out.println(hasPathSum(node, 100));
    }

    public static boolean hasPathSum(TreeNode root, int targetSum) {
        return hasResult(root, targetSum, 0);
    }

    private static boolean hasResult(TreeNode root, int targetSum, int sumNow) {
        if (root == null)   return false;

        sumNow += root.val;
        if ((root.left == null && root.right == null) && sumNow == targetSum) {
            return true;
        }
        return hasResult(root.left, targetSum, sumNow) || hasResult(root.right, targetSum, sumNow);
    }
    
}
